#!/bin/bash
# Copyright (C) 2019 Checkmk GmbH - License: GNU General Public License v2
# This file is part of Checkmk (https://checkmk.com). It is subject to the terms and
# conditions defined in the file COPYING, which is part of this source code package.

# Reason for this no-op: shellcheck disable=... before the first command disables the error for the
# entire script.
:

# Disable unused variable error (needed to keep track of version)
# shellcheck disable=SC2034
CMK_VERSION="2.5.0b1"

if type lpstat >/dev/null 2>&1; then
    export LC_TIME="en_US.UTF-8"
    echo "<<<cups_queues>>>"
    CPRINTCONF=/etc/cups/printers.conf
    if [ -r "$CPRINTCONF" ]; then
        LOCAL_PRINTERS=$(perl -ne '/<(?:Default)?Printer ([\w-]+)>/ && print "$1\n"' $CPRINTCONF)
        # SC2162: read without -r will mangle backslashes.
        # We suppress it here for compatibility (curretly backslashes e.g. before spaces are dropped).
        # Since escaping of field seperators is not relevant when reading into one variable, we probably
        # would have wanted "read -r".
        # shellcheck disable=SC2162
        lpstat -h localhost -p | while read LINE; do
            PRINTER=$(echo "$LINE" | awk '{print $2}')
            if echo "$LOCAL_PRINTERS" | grep -q "$PRINTER"; then
                echo "$LINE"
            fi
        done
        echo '---'
        # SC2162: read without -r will mangle backslashes.
        # We suppress it here for compatibility (curretly backslashes e.g. before spaces are dropped).
        # Since escaping of field seperators is not relevant when reading into one variable, we probably
        # would have wanted "read -r".
        # shellcheck disable=SC2162
        lpstat -h localhost -o | while read LINE; do
            PRINTER=${LINE%%-*}
            if echo "$LOCAL_PRINTERS" | grep -q "$PRINTER"; then
                echo "$LINE"
            fi
        done
    else
        PRINTER=$(lpstat -p)
        echo "$PRINTER"
        echo '---'
        QUEUE=$(lpstat -o | sort)
        echo "$QUEUE"
    fi
fi
